package com.hs.shirodemo2.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.shirodemo2.constant.CommonConstant;
import com.hs.shirodemo2.entity.SysRole;
import com.hs.shirodemo2.mapper.SysRoleMapper;
import com.hs.shirodemo2.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public void add(SysRole entity) {
        sysRoleMapper.insert(entity);
        if(!CollectionUtils.isEmpty(entity.getPermissionIdList())){
            sysRoleMapper.insertRolePermission(entity);
        }
    }

    @Override
    public void edit(SysRole entity) {
        sysRoleMapper.update(entity);
        if(entity.getPermissionIdList() != null){
            sysRoleMapper.deleteRolePermission(entity.getId()); // 先删除
            if(!CollectionUtils.isEmpty(entity.getPermissionIdList())){
                sysRoleMapper.insertRolePermission(entity); // 再新增
            }
        }
    }

    @Override
    public void remove(Integer id) {
        sysRoleMapper.delete(id);
    }

    @Override
    public void removeBatch(Integer[] ids) {
        sysRoleMapper.deleteBatch(ids);
    }

    @Override
    public List<SysRole> find(SysRole entity) {
        return sysRoleMapper.select(entity);
    }

    @Override
    public Map<String, Object> findPage(Integer pageNum, Integer pageSize, SysRole entity) {
        //分页业务
        PageHelper.startPage(pageNum, pageSize);
        List<SysRole> list = sysRoleMapper.select(entity);
        PageInfo<SysRole> pageInfo = new PageInfo<>(list);
        //1.当前页面数据（数据列表）2.此次查询的总记录数
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put(CommonConstant.PAGE_LIST, list);
        pageMap.put(CommonConstant.PAGE_TOTAL, pageInfo.getTotal());
        return pageMap;
    }

    @Override
    public SysRole findById(Integer id) {
        return sysRoleMapper.selectById(id);
    }

    @Override
    public HashSet<String> findRoleCodeById(Integer userId) {
        return sysRoleMapper.getRoleCodeById(userId);
    }
}